<?php

namespace app\admin\controller;

use app\admin\model\channel\Channel;
use app\admin\model\order as OrderModel;
use app\admin\model\merchant\MerchantModel;
use app\Request;
use think\facade\Log;
use think\facade\Session;
use ulit\CryptAES;
use ulit\thirdPayment\SafePay;
use ulit\thirdPayment\CanLangPay;
use yzh52521\EasyHttp\Http;

class Order extends Base
{


    public function list(){


        $merchant_info = session('merchant_info');
        $role_info=session('role_info');
        $role_info['type']!=1 && $where['merchant_id']=$merchant_info['id'];
        $where['status']=1;
        $total_money=OrderModel\Order::where($where)->sum('amount');
        $actual_amount=OrderModel\Order::where($where)->sum('actual_amount');
        $commission=OrderModel\Order::where($where)->sum('commission');
        return view('order/list',['total_money'=>$total_money,'actual_amount'=>$actual_amount,'commission'=>$commission]);

    }

    public function ajaxList(): \think\response\Json
    {

         $list= OrderModel\Order::list();

         return $this->result($list);
    }

    public function callbackOrder(Request $request)
    {
        if ($request->isPost() && $request->isAjax()) {
            $order_sn=$request->param('order_sn');

            $Order = OrderModel\Order::where(['order_sn'=>$order_sn])->find();

            $Order->status =1;
            $Order->save();
            $ext=$Order->third_ext_json;
            $arr=[
                'order_sn'=>$order_sn,
                'out_biz_no'=>$order_sn,
                'order_id'=>$order_sn,
                'status'=>1,
                'pay_date'=>date('Y-m-d H:i:s'),
            ];
            $aec = new CryptAES();
            $Merchant=MerchantModel::where(['id' => $Order['merchant_id']])->field(['key','appid','secret'])->find();
            $pasta=$aec->aesEncode(json_encode($arr,JSON_UNESCAPED_UNICODE),$Merchant['key']);
            $send['code']=200;
            $send['msg']='success';
            $send['data']=$pasta;
            $dd=Http::asJson()->post($ext['notify_url'], $send);
            Log::write("已经回调地址".$ext['notify_url'].'data->'.json_encode($arr,JSON_UNESCAPED_UNICODE));
            Log::write("回调结果".$ext['notify_url'].'data->'.json_encode($dd->array(),JSON_UNESCAPED_UNICODE));
            return $this->success();
        }
        return $this->error();
    }

    public function findOrder(Request $request)
    {
        if ($request->isPost() && $request->isAjax()) {
            $order_sn=$request->param('order_sn');
            $Order = OrderModel\Order::where(['order_sn'=>$order_sn])->find();
            $Channel=Channel::where(['id'=>$Order->channel_id])->value('code');

            if($Channel=='Safe'){
                $result=$this->SafeOrderInfo($order_sn);

                return $this->success($result);
            }elseif($Channel=='Canlang'){
                $result=$this->CanLangOrder($order_sn);
                if($result['code']==200){
                    return $this->success($result);
                }else{
                    return $this->error($result['msg']);
                }



            }

        }
        return $this->error();

    }

    public function CanLangOrder($order_sn)
    {
        return CanLangPay::getInstance()->query($order_sn);

    }

    public function SafeOrderInfo($order_sn)
    {
        $result=SafePay::getInstance()->query($order_sn);
        $res=json_decode($result,true);
        if($res['result']['orderStatus']==4){
            $msg=$res['result']['remark'];
        }else{
            $res['message']?$msg=$res['message']:$msg='数据异常';
        }

        return ['code'=>200,'msg'=>$msg,'data'=>$res['result']];
    }

    public function payOrder(Request $request): \think\response\View|\think\response\Json
    {


        if($request->isPost() && $request->isAjax()){
            $admin_id=3;
            $MemberKeyInfo= MerchantModel::where(['admin_id'=>$admin_id])->find(); //获取商户密钥
            $out_trade_id=getRandOrderSn('test');
            $data=$request->param();
            $data['out_trade_id']=$out_trade_id;
            $data=[
                'card_no'=>$data['card_no'],
                'appid'=>$MemberKeyInfo->appid,
                'secret'=>$MemberKeyInfo->secret,
                'name'=>$data['name'],
                'out_trade_id'=>$out_trade_id,
                'withdraw_type'=>$data['withdraw_type'],//0：记账本代付到支付宝账户 1：记账本代付到卡
                'remark'=>$data['body'],
                'amount'=>1.5,
               // 'show_name'=>false, 	记账本代付到户商家别名：true （固定值 为启用别
                'account_type'=>$data['withdraw_type'],
                'channel_code'=>'Canlang',
                'notify_url'=>$request->domain().'/api.php/Payment/notify'
            ];
            $sign=makeApiSign($data,$MemberKeyInfo->key);
            $data['sign']=$sign;
            // $result=httpRequest('http://test.com//api.php/Payment/pay','POST',$data,[]);


            $promise = Http::asJson()->post($request->domain().'/api.php/Payment/pay',$data);


            return  $this->success($promise->array());
        }


        return view('order/pay');
    }

    public function delOrder(Request $request)
    {

        OrderModel\Order::where(['order_sn'=>$request->param('order_sn')])->delete();
        return $this->success();
    }

    public function downloadOrder(Request $request)
    {
        $result=CanLangPay::getInstance()->orderBill($request->param('order_sn'));



        $download_url=$result['data']['download_url'];

        if($download_url){
            return $this->success(['name'=>date('YmdHis',time())."证明下载",'url'=>$download_url]);
        }else{
            return $this->error("未找到转账记录");
        }

    }

}